import { createRouter, createWebHistory } from 'vue-router';
import {generateDynamicRoutes} from "./dynamicRoutes.js";

import { useAuthStore } from '@/stores/authStore.js';
import { useThemeStore } from '@/stores/themeStore.js';

// 导入页面组件 (使用路由懒加载)
const Home = () => import('@/views/HomeView.vue');
const Main = () => import('@/views/MainView.vue');

// 定义路由规则
const routes = [
    {
        path: '/',
        name: 'Main',
        component: Main,
        redirect: '/index', // 默认重定向到 /index
        meta: {
            requiresAuth: true // 路由元信息示例
        },
        children: [
            {
                path: '/index',
                name: 'Home',
                component: Home
            }
        ]
    },
    {
        path:'/login',
        name:'Login',
        component:()=> import('@/views/LoginView.vue')
    },
    {
        path:'/register',
        name:'Register',
        component:()=> import('@/views/user/RegisterView.vue')
    }

];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();
    const themeStore = useThemeStore();
    const requiresAuth = to.matched.some(record => record.meta?.requiresAuth);

    //设置当前面包屑
    themeStore.setBreadcrumbs(to);

    //判断用户是否已经加载动态路由
    if (authStore.isLoggedIn() && !authStore.hasLoadedDynamicRoutes) {
        console.log('用户已经登录，加载动态路由')
        // 加载动态路由
        addRoutes(authStore.menuList)
        authStore.hasLoadedDynamicRoutes = true
        return next({path: to.fullPath, replace: true})
    }
    if (requiresAuth && !authStore.isLoggedIn()) {
        next('/login'); // 未登录，重定向到登录页
    } else {
        next(); // 已登录，继续导航
    }
})

//动态添加路由
export function addRoutes(menuList){
    const newRoutes = generateDynamicRoutes(menuList)
    newRoutes.forEach(route => {
            router.addRoute('Main',route);
    })

    console.log('动态路由添加成功',router.getRoutes())

    // 添加404路由（必须在动态路由后添加）
    router.addRoute('Main',{
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue')
    });

}

export default router;